import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
import {formatTime} from '../../../utils/util'
const requests = require("../../../utils/request")

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    address:{},
    hasAddress: false,
    total:0,
    orders:[],
    addressIcon:'/imgs/myaddress.png'
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const allOrders = JSON.parse(options.orders)
    const orders=[]
    for(let i = 0;i<allOrders.length;i++)
    {
      if(allOrders[i].selected)
      {
        orders.push(allOrders[i])
      }
    }
    this.setData({
      orders
    })
    this.getTotalPrice();
  },
  /**
   * 计算总价
   */
  getTotalPrice() {
    let orders = this.data.orders;
    let total = 0;
    for(let i = 0; i < orders.length; i++) {
      total += orders[i].num * orders[i].price;
    }
    this.setData({
      total: total
    })
  },
  /**
   * 获取内存中的地址缓存
   */
  getAddressinStorage()
  {
    const self = this;
    wx.getStorage({
      key:'address',
      success(res) {
        self.setData({
          address: res.data,
          hasAddress: true
        })
      }
    })
  },
  /**
   * 支付
   */
  async toPay() {
    var that = this
    if(!this.data.hasAddress)
    {
      wx.showToast({
        title: '请选择地址',//提示文字
        duration:2000,//显示时长
        mask:true,//是否显示透明蒙层，防止触摸穿透，默认：false  
        icon:'error', //图标，支持"success"、"loading"  
      })
    }
    else{
    wx.showModal({
      title: '温馨提示',
      content: `本次积分兑换将消耗您${this.data.total}积分`,
      text:'center',
      success: async (res)=> {
        if (res.confirm) {
          console.log('用户点击确定')
        
        //获取原有积分
        let result1 = await requests.getUserById(app.globalData.openid)
        // console.log(result1.data.data.value)
        let curIntegration = result1.data.data.value.integration-that.data.total
        if(curIntegration>0)
        {
        //扣除积分
        let result2 = await requests.userInterface(null,curIntegration,null,app.globalData.openid,null,null,null,app.globalData.openid,'update')
        console.log(result2)

        const {address,orders} = this.data
        //提交商品订单
        let res1= await requests.storeInterface(address.addressId,orders[0].id,orders[0].num,null,orders[0].price,0,formatTime(new Date()),app.globalData.openid,'add')
        for(let i=1;i<orders.length;i++)
        {
          await requests.storeInterface(address.addressId,orders[i].id,orders[i].num,res1.data.data.value.orderId,orders[i].price,0,formatTime(new Date()),app.globalData.openid,'add')
        }

        Toast({
          duration: 2000, // 持续展示 toast
          forbidClick: true,
          type: 'sucess',
          message: '兑换成功',
        });
        setTimeout(()=>{
          app.globalData.orderPageActive=2

          wx.switchTab({
            url: '../../order/index'
          })
          
        },2000)




        }
        else
        {
          //提示积分不足，无法兑换
          Toast({
            duration: 2000, // 持续展示 toast
            forbidClick: true,
            type: 'fail',
            message: '积分不足，无法兑换',
          });
          setTimeout(()=>{
            wx.switchTab({
              url: '../../mine/index'
            })
          },2000)

        }

        }
      
        else if (res.cancel) {
          console.log('用户点击取消')
        }}
    })
  }
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getAddressinStorage();

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})